using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using XfTechOAWeb.IService;

namespace XfTechOAWeb.Service.Background
{
    /// <summary>
    /// 定时服务
    /// </summary>
    public class TimedHostedService : BackgroundService
    {
        private readonly IServiceProvider _serviceP; 
        private Timer _timer;   //定时器

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="serviceP"></param>
        public TimedHostedService(IServiceProvider serviceP)
        {
            _serviceP = serviceP;
        }

        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(10)); //定时器创建后马上执行，每10秒钟执行一次

            return Task.CompletedTask;
        }

        /// <summary>
        /// 定时器具体执行的方法
        /// </summary>
        /// <param name="state"></param>
        private void DoWork(object state)
        {
            //做一些事情
            //using(var scope = _serviceP.CreateScope())
            //{
            //    var userService = scope.ServiceProvider.GetRequiredService<IUserService>();

            //    userService.GetUserCount();
            //}
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public override void Dispose()
        {
            _timer?.Dispose();  //如果_timer对象不为null，则销毁

            base.Dispose();
        }

    }
}